﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using Global;

namespace DataAccess
{
    public class DataProvider
    {
        private static string _connectionString;
            //= @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
            //+ AppDomain.CurrentDomain.BaseDirectory + @"Database\Database.accdb";
            //+ Settings.CURRENT_FILE_PATH;
        
        private static OleDbConnection _connection = null;
        private static OleDbCommand _command = null;

        public static void OpenConnection(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
                _connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Settings.CURRENT_FILE_PATH;
            else
                //Update the connection string whenever the path changed
                _connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath;
            
            _connection = new OleDbConnection(_connectionString);
            _connection.Open();
        }

        public static void CloseConnection()
        {
            _connection.Close();
            _connection = null;
        }

        public static void ExecuteNonquery(string query)
        {
            if (_connection != null)
            {
                try
                {
                    _command = new OleDbCommand(query, _connection);
                    _command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public static OleDbDataReader ExecuteReader(string query)
        {
            if (_connection != null)
            {
                try
                {
                    _command = new OleDbCommand(query, _connection);
                    return _command.ExecuteReader();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return null;
        }
    }
}
